package com.jinzihan.www.util;

import java.util.Scanner;

/**
 * @author jin-zihan
 * @create 2021-11-19-15:56
 */
public class CMUtility {
    private static final Scanner scanner=new Scanner(System.in);
    public static char readMenuSelection(){
        char c;
        for(;;){
            String str=readKeyBoard(1,false);
            c=str.charAt(0);
            if(c!='1'&&c!='2'&&c!='3'&&c!='4'&&c!='5'){
                System.out.println("选择错误，请重新输入：");
            }else break;
        }
        return c;
    }

    public static int readInt(){
        int n;
        for(;;){
            String str=readKeyBoard(100,false);
            try{
                n=Integer.parseInt(str);
                break;
            }catch (NumberFormatException e){
                System.out.println("数字输入错误，请重新输入：");
            }
        }
        return n;
    }
    /*
    读入数字 如果没有输入 则返回默认值defaultValue
     */
    public static int readInt(int defaultValue){
        int n;
        for(;;){
            String str=readKeyBoard(2,true);
            if(str.equals("")){
                return defaultValue;
            }
            try{
                n=Integer.parseInt(str);
                break;
            }catch (NumberFormatException e){
                System.out.println("数字输入错误，请重新输入：");
            }
        }
        return n;
    }
    public static String readString(int limit){
        return readKeyBoard(limit,false);
    }
    /*
    读入长度限制为limit的数，如果没有输入，则返回默认的defaultValue
     */
    public static String readString(int limit,String defaultValue){
        String str=readKeyBoard(limit,true);
        return str.equals("")?defaultValue:str;
    }
    /*
    确认选择的函数 如果为是则返回y，不是则返回N
     */
    public static char readConfirmSelection(){
        char c;
        for(;;){
            String str=readKeyBoard(1,false).toUpperCase();
            c=str.charAt(0);
            if(c=='Y'||c=='N'){
                break;
            }else{
                System.out.println("选择错误，请重新输入：");
            }
        }
        return c;
    }
    /*
    读取键盘的下一个输入   blankReturn的意思是当输入的为空格时，是否返回
     */
    public static String readKeyBoard(int limit,boolean blankReturn){
        String line="";
        while(scanner.hasNextLine()){
            line= scanner.nextLine();
            if(line.length()==0){
                if(blankReturn) return line;
                else continue;
            }
            if(line.length()>limit){
                System.out.println("输入长度（不大于"+limit+"）错误，请重新输入");
                continue;
            }
            break;
        }
        return line;
    }
}
